package com.ts.cloudalibabaconsumer8084.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.ts.cloudalibabacommons.domain.JsonResult;
import com.ts.cloudalibabaconsumer8084.service.IFeignService;
import com.ts.cloudalibabaconsumer8084.service.OpenFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class DemoController {
    @Value("${service-url.nacos-user-service}")
    private String SERVICE_URL;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    OpenFeignService openFeignService;
    @Autowired
    IFeignService feignService;

    @GetMapping("/getInfo/{id}")
    public JsonResult<String> getInfo(@PathVariable("id") Long id){
        if(id>3){
            throw new RuntimeException("no such id!");
        }
        return feignService.msbSql(id);
    }

    @GetMapping("/consumer/openfeignFallBack/{id}")
    @SentinelResource(value = "openfeignFallBack",fallback = "fallbackHandler")
    public JsonResult<String> openfeignFallBack(@PathVariable Long id){
        if(id<=3){
            return openFeignService.msbSql(id);
        }else {
            throw new RuntimeException("no records!");
        }
    }

    @GetMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback",fallback = "fallbackHandler")
    public JsonResult<String> fallback(@PathVariable Long id){
        if(id<=3){
            return restTemplate.getForObject(SERVICE_URL+"/info/"+id,JsonResult.class);
        }else {
            throw new RuntimeException("no records!");
        }
    }

    public JsonResult<String> fallbackHandler(Long id,Throwable e){
        JsonResult<String> result = new JsonResult<>(444,"未知商品ID");
        return result;
    }

    @GetMapping("/consumer/timeout")
    public JsonResult<String> timeout(){
        return openFeignService.timeout();
    }
}
